package com.idak.rdv.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.idak.rdv.dao.GenericDao;

@Transactional
public abstract class RdvHibernateDao<T,PK extends Serializable> implements GenericDao<T, PK > {
	
	@Autowired
	private SessionFactory sessionFactory;

	@SuppressWarnings("unchecked")
	public T findById(PK primaryKey) {
		Session session = sessionFactory.getCurrentSession();
		return (T) session.get(getEntityClass(), primaryKey);
	}

	@SuppressWarnings("unchecked")
	public List<T> getAll() {
		Session session = sessionFactory.getCurrentSession();
		String query = "from "+getEntityClass().getName();
		return session.createQuery(query).list();
	}

	public void update(T object) {
		Session session = sessionFactory.getCurrentSession();
		session.saveOrUpdate(object);
	}

	public void delete(T object) {
		Session session = sessionFactory.getCurrentSession();
		session.delete(object);
	}

	public void create(T object) {
		Session session = sessionFactory.getCurrentSession();
		session.persist(object);
	}
	
	public Session getCurrentSession(){
		return sessionFactory.getCurrentSession();
	}
	
	public abstract Class<T> getEntityClass();
}
